package com.xln.kafka.sample.sample;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

@Slf4j
public class ConsumerQuickStart {

    public static void main(String[] args) {

        Properties properties = new Properties();
        properties.put("bootstrap.servers","192.168.200.130:9092");
        properties.put("group.id","group1");
        properties.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);

        KafkaConsumer consumer   = new KafkaConsumer(properties);
//        consumer.subscribe(Arrays.asList("topic-first"));

        /*while (true){
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.key());
                System.out.println(consumerRecord.value());
                System.out.println(consumerRecord.offset());
                System.out.println(consumerRecord.partition());

               *//* try {
                    //同步提交偏移量
                    consumer.commitSync();
                }catch (CommitFailedException e){
                    System.out.println("记录提交失败的异常："+e);
                }*//*
            }
            //异步的方式提交偏移量
            *//*consumer.commitAsync(new OffsetCommitCallback() {
                @Override
                public void onComplete(Map<TopicPartition, OffsetAndMetadata> map, Exception e) {
                    if(e != null){
                        System.out.println("记录错误的提交偏移量："+map+",异常信息为："+e);
                    }
                }
            });*//*



        }*/
        consumer.subscribe(Arrays.asList("stream-quickstart-out"));
        try {
            while (true){
                ConsumerRecords<String,String> poll = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String,String> record : poll){

                    System.out.println(record.key());
                    System.out.println(record.value());

                }
                //异步提交偏移量
                consumer.commitAsync();
            }
        } catch (Exception e) {
            log.info("异常：{}" ,e, e);

        } finally {
            consumer.commitSync();
        }


    }


}
